package com.shanshan.dubborpc.netty;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description
 * @ClassName NettyClient
 * @Author 山山大魔王
 * @Date 2022/9/2 14:21
 * @Version 1.0
 */
public class NettyClient {

    // 创建线程池
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static NettyClientHandler client;

    // 编写方法使用代理模式，获取一个代理对象

    public Object getBean(final Class<?> serivceClass , final String providerName){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serivceClass},
                (proxy,method,args)->{
           // {} 每调用一次，客户端调用一次hello，就会进入该代码
            if(client == null ){
               initClient();
           }

           // 设置发给服务端的信息
            client.setPara(providerName + args[0]);


           return executor.submit(client).get();
        });
    }

    // 初始化客户端
    private static void initClient(){

        client = new NettyClientHandler();

        // 创建EventLoopGroup
        EventLoopGroup group = new NioEventLoopGroup();


            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast(new StringEncoder());

                            pipeline.addLast(new StringDecoder());

                            pipeline.addLast(client);
                        }
                    });

        try {
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8081).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }


}
